package dao

import (
	"github.com/go-xorm/xorm"
	"log"
	"lottery/models"
)

type ResultDao struct {
	engine *xorm.Engine
}

func NewResultDao(engine *xorm.Engine) *ResultDao {
	return &ResultDao{engine: engine}
}

func (d *ResultDao) Get(id int) *models.TbResult {
	data := &models.TbResult{Id: id}
	ok, err := d.engine.Get(data)
	if ok && err == nil {
		return data
	} else {
		data.Id = 0
		return data
	}
}

func (d *ResultDao) GetAll() []models.TbResult {
	dataList := make([]models.TbResult, 0)
	err := d.engine.Find(&dataList)
	if err != nil {
		log.Println("result_dao.GetAll() failed, err=", err)
	}
	return dataList
}

func (d *ResultDao) GetByWinner(userId int) []models.TbResult {
	dataList := make([]models.TbResult, 0)
	err := d.engine.
		Where("winner_id=?", userId).
		Asc("create_time").
		Find(&dataList)
	if err != nil {
		log.Println("result_dao.GetByWinner() failed, err=", err)
	}
	return dataList
}

func (d *ResultDao) GetByAward(awardId int) []models.TbResult {
	dataList := make([]models.TbResult, 0)
	err := d.engine.
		Where("award_id=?", awardId).
		Asc("create_time").
		Find(&dataList)
	if err != nil {
		log.Println("result_dao.GetByAward() failed, err=", err)
		return dataList
	} else {
		return dataList
	}
}

func (d *ResultDao) GetByEvent(eventId int) []models.TbResult {
	dataList := make([]models.TbResult, 0)
	err := d.engine.
		Where("event_id=?", eventId).
		Desc("create_time").
		Find(&dataList)
	if err != nil {
		log.Println("result_dao.GetByAward() failed, err=", err)
		return dataList
	} else {
		return dataList
	}
}

func (d *ResultDao) CountAll() int64 {
	count, err := d.engine.Count(&models.TbResult{})
	if err != nil {
		log.Println("result_dao.CountAll() failed, err=", err)
		return 0
	}
	return count
}

func (d *ResultDao) CountByEvent(eventId int) int64 {
	count, err := d.engine.Where("event_id=?", eventId).Count(&models.TbResult{})
	if err != nil {
		log.Println("result_dao.CountByEvent() failed, err=", err)
		return 0
	}
	return count
}

func (d *ResultDao) CountByAward(awardId int) int64 {
	count, err := d.engine.Where("award_id=?", awardId).Count(&models.TbResult{})
	if err != nil {
		log.Println("result_dao.CountByAward() failed, err=", err)
		return 0
	}
	return count
}

func (d *ResultDao) CountByWinner(winnerId int) int64 {
	count, err := d.engine.Where("winner_id=?", winnerId).Count(&models.TbResult{})
	if err != nil {
		log.Println("result_dao.CountByWinner() failed, err=", err)
		return 0
	}
	return count
}

func (d *ResultDao) Update(data *models.TbResult, columns []string) error {
	_, err := d.engine.Where("id=?", data.Id).MustCols(columns...).Update(data)
	return err
}

func (d *ResultDao) Create(data *models.TbResult) error {
	_, err := d.engine.Insert(data)
	return err
}
